// str1 str2 
const str1 = "test";
const str2 = "teest";
const str3 = "teeest";
const str4 = "teesst";
const str5 = "teessst";

function check(str1, str2) {
    if (str1.length > str2.length)
        return false;
    const len = str2.length;
    for (let i = 0; i < len; i++) {
        let temp = str2;
        temp = temp.splice(i, 1);
        if (temp === str1)
            return true;
    }
    return false;
}

const arr = [str1, str2, str3, str4, str5];

// 1 2
//   2 
// check=true +1 max(+1, origin)

function returnChain(arr) {
    
    
    let res = [];

    for (let i = 0; i < arr.length - 1; i++) {
        if (res.length === 0) {
            if (check(arr[i], arr[i + 1])) {
                if (res.length === 0) {
                    res.push(arr[i]);
                    res.push(arr[i + 1]);
                } else {
                    res.push(arr[i + 1]);
                }
            }
        }
        
    }
}

/**
 * 
const str1 = "test";
const str2 = "teest";
const str3 = "teeest";
const str4 = "teesst";
const str5 = "teessst";
 */

function func2(arr) {
    arr.sort((a, b) => b.length - a.length);
    const mySet = new Set(...arr);
    let res = [];
    res.push(arr[0]);
    for (let i = 1; i < arr.length; i++) {
        let temp = res[res.length - 1];
        if (temp.length === arr[i].length + 1) {
            for (let j = 0; j < temp.length; j++) {
                // let cur = temp.splice(j, 1);
                let cur = temp.slice(0, j).concat(temp.slice(j + 1));
                if (mySet.has(cur)) {
                    res.push(cur);
                    break;
                }
            }
        }
    }
    return res;
}


function func(arr) {
    arr.sort((a, b) => a.length - b.length);
    let res = [];
    // res.push(arr[0]);
    for (let i = 0; i < arr.length; i++) {
        if (res.length === 0) {
            let cur = arr[i];
            for (let j = i + 1; j < arr.length; j++) {
                if (cur.length === arr[j].length - 1) {
                    if (check(cur, arr[j])) {
                        res.push(cur);
                        res.push(arr[j]);
                        break;
                    }
                }
            }
        } else {
            let temp = res[res.length - 1];
            if (temp.length === arr[i].length - 1) {
                if (check(temp, arr[i]))
                    res.push(arr[i]);
            }
        }
    }
    return res;
}
